{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Quantum Fourier Transform "
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Classical Fourier transforms aid many areas such as signal processing and data compression. Below, we quantize it to enable Quantum Fourier Transforms (QFT) in CUDA-Q.\n",
    "\n",
    "QFT is a key ingredient in Shor's algorithm which is exponentially faster at factoring prime numbers and also plays a vital role in many other interesting quantum algorithms. \n",
    "\n",
    "The idea with classical Fourier transforms is to take the problem from the frequency domain, to the time domain where it is easier to solve. This is the same analogy we draw with QFT, where we take the basis state from the computational basis to the Fourier basis. "
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Quantum Fourier Transform is defined to be the linear operation which takes a basis state, $\\ket{x}$, \n",
    "\n",
    "\n",
    "$$\n",
    "\\begin{equation} \n",
    "\\text{QFT}\\ket{x}  =   \\frac{1}{\\sqrt{N}}\\sum_{y=0}^{N-1} e^{\\frac{2\\pi ixy}{N}} \\ket{y}\n",
    "\\tag{1}\n",
    "\\end{equation}\n",
    "$$\n",
    "\n",
    "where $n$ is the number of qubits and $N= 2^n$. \n",
    "\n",
    "It is convenient to represent states like $\\ket{x}  = \\ket{101}$ in their binary representation which in this case would be $2^2 \\times 1 + 2^1 \\times 0 + 2^0 \\times 1 = \\ket{5}$. \n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For the $n=1$ qubit case, we have the following basis states: $\\ket{0}, \\ket{1}$. The QFT on these is as follows: \n",
    "\n",
    "$$\n",
    "\\begin{equation} \n",
    "\\begin{aligned}\n",
    "\\text{QFT}|0\\rangle &= \\frac{1}{\\sqrt{2}}\\sum_{y=0}^{2-1} e^{\\frac{2\\pi i(0)y}{2}}|y\\rangle \\\\\n",
    "&= \\frac{1}{\\sqrt{2}}\\left(e^0|0\\rangle + e^0|1\\rangle\\right) \\\\\n",
    "&= \\frac{1}{\\sqrt{2}}(|0\\rangle + |1\\rangle) \\\\\n",
    "&= \\ket{+} \\\\\n",
    "\\end{aligned}\n",
    "\\tag{2}\n",
    "\\end{equation}\n",
    "$$\n",
    "\n",
    "$$\n",
    "\\begin{equation} \n",
    "\\begin{aligned}\n",
    "\\text{QFT}|1\\rangle &= \\frac{1}{\\sqrt{2}}\\sum_{y=0}^{2-1} e^{\\frac{2\\pi i(1)y}{2}}|y\\rangle \\\\\n",
    "&= \\frac{1}{\\sqrt{2}}\\left(e^0|0\\rangle + e^{\\pi i}|1\\rangle\\right) \\\\\n",
    "&= \\frac{1}{\\sqrt{2}}(|0\\rangle - |1\\rangle) \\\\\n",
    "&= \\ket{-} \\\\\n",
    "\\end{aligned}\n",
    "\\tag{3}\n",
    "\\end{equation}\n",
    "$$\n",
    "\n",
    "             \n",
    "\n",
    "To summarize, $\\text{QFT}|0\\rangle = \\ket{+}$ and $\\text{QFT}|1\\rangle = \\ket{-}$ which can be achieved by applying Hadamard gates. \n",
    "\n",
    "\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "Let us now extend this and see how we can apply this to $n=3$ qubits. \n",
    "\n",
    "For $n=3, N = 2^3 = 8$ and we would like to perform $\\text{QFT}|101\\rangle$ which in binary is $2^2 \\times 1 + 2^1 \\times 0 + 2^0 \\times 1 = 5$: \n",
    "\n",
    "$$\n",
    "\\begin{equation} \n",
    "\\begin{aligned}\n",
    "\\text{QFT}|101\\rangle = \\text{QFT}|5\\rangle &= \\frac{1}{\\sqrt{8}}\\sum_{y=0}^{8-1} e^{\\frac{2\\pi i(5)y}{8}}|y\\rangle \\\\\n",
    "&= \\frac{1}{\\sqrt{8}} [ e^{0}\\ket{0} + e^{\\frac{5i\\pi (1)}{4}}\\ket{1}  + e^{\\frac{5i\\pi (2)}{4}}\\ket{2} +...++ e^{\\frac{5i\\pi (7)}{4}}\\ket{7} ]   \\\\\n",
    "&= \\frac{1}{\\sqrt{8}} [ \\ket{000} + e^{\\frac{5i\\pi (1)}{4}}\\ket{001}  + e^{\\frac{5i\\pi (2)}{4}}\\ket{010} +...++ e^{\\frac{5i\\pi (7)}{4}}\\ket{111} ]   \\\\\n",
    "&=  (0.35+0i) \\ket{000} + (-0.25-0.25i)\\ket{001}  + (0+0.35i)\\ket{010} +...+ (-0.25+0.25i)\\ket{111}    \\\\\n",
    "\\end{aligned}\n",
    "\\tag{4}\n",
    "\\end{equation}\n",
    "$$\n",
    "\n",
    "where we have used the fact that $e^{i\\theta} = \\cos(\\theta) + i\\sin(\\theta).$\n",
    "\n",
    "Here, we see how in addition to the Hadamard gates, we need some phase gates to apply the appropriate phases to the basis states. It turns out that the gate we need is the controlled $R_k$ rotation where the $R_k$ gate is denoted by:\n",
    "\n",
    "\n",
    "\n",
    "$$\n",
    "\\begin{equation} \n",
    "R_k = \\begin{bmatrix}\n",
    "1 & 0 \\\\\n",
    "0 & e^{2\\pi i/ 2^{k}}\n",
    "\\end{bmatrix}\n",
    "\\tag{5}\n",
    "\\end{equation}\n",
    "$$\n",
    "\n",
    "\n",
    "\n",
    "Here is a generalized ciruit for a $n$-qubit quantum Fourier transform:"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "<img src=\"images/qft.png\" alt=\"qft\" width=\"600\">\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Below we show the code for a QFT implementation in CUDA-Q based on the circuit diagram above: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cudaq\n",
    "import numpy as np\n",
    "from typing import List\n",
    "\n",
    "\n",
    "@cudaq.kernel\n",
    "def quantum_fourier_transform(input_state: List[int]):\n",
    "    '''Args: \n",
    "    input_state (list[int]): specifies the input state to be Fourier transformed.  '''\n",
    "\n",
    "    qubit_count = len(input_state)\n",
    "\n",
    "    # Initialize qubits.\n",
    "    qubits = cudaq.qvector(qubit_count)\n",
    "\n",
    "    # Initialize the quantum circuit to the initial state.\n",
    "    for i in range(qubit_count):\n",
    "        if input_state[i] == 1:\n",
    "            x(qubits[i])\n",
    "\n",
    "    # Apply Hadamard gates and controlled rotation gates.\n",
    "    for i in range(qubit_count):\n",
    "        h(qubits[i])\n",
    "        for j in range(i + 1, qubit_count):\n",
    "            angle = (2 * np.pi) / (2**(j - i + 1))\n",
    "            cr1(angle, [qubits[j]], qubits[i])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     ╭───╮╭───╮╭───────────╮╭────────────╮                       \n",
      "q0 : ┤ x ├┤ h ├┤ r1(1.571) ├┤ r1(0.7854) ├───────────────────────\n",
      "     ╰───╯╰───╯╰─────┬─────╯╰─────┬──────╯╭───╮╭───────────╮     \n",
      "q1 : ────────────────●────────────┼───────┤ h ├┤ r1(1.571) ├─────\n",
      "     ╭───╮                        │       ╰───╯╰─────┬─────╯╭───╮\n",
      "q2 : ┤ x ├────────────────────────●──────────────────●──────┤ h ├\n",
      "     ╰───╯                                                  ╰───╯\n",
      "\n",
      "[ 0.35+0.j   -0.25-0.25j  0.  +0.35j  0.25-0.25j -0.35+0.j    0.25+0.25j\n",
      " -0.  -0.35j -0.25+0.25j]\n"
     ]
    }
   ],
   "source": [
    "#Can be changed to 'nvidia' for single gpu, 'nvidia-mgpu' for multi-GPU or quantum hardware.\n",
    "cudaq.set_target(\"qpp-cpu\")\n",
    "\n",
    "# The state to which the QFT operation is applied to. The zeroth element in the list is the zeroth qubit.\n",
    "input_state = [1, 0, 1]\n",
    "\n",
    "# Number of decimal points to round up the statevector to.\n",
    "precision = 2\n",
    "\n",
    "# Draw the quantum circuit.\n",
    "print(cudaq.draw(quantum_fourier_transform, input_state))\n",
    "\n",
    "# Print the statevector to the specified precision\n",
    "statevector = np.array(cudaq.get_state(quantum_fourier_transform, input_state))\n",
    "print(np.round(statevector, precision))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can verify that this is the correct answer as above we worked out that: \n",
    "\n",
    "$$\n",
    "\\begin{equation} \n",
    "\\begin{aligned}\n",
    "\\text{QFT}|101\\rangle = \\text{QFT}|5\\rangle &= \\frac{1}{\\sqrt{8}}\\sum_{y=0}^{8-1} e^{\\frac{2\\pi i(5)y}{8}}|y\\rangle \\\\\n",
    "&=  (0.35+0i) \\ket{000} + (-0.25-0.25i)\\ket{001}  + (0+0.35i)\\ket{010} +...+ (-0.25+0.25i)\\ket{111}.   \\\\\n",
    "\\end{aligned}\n",
    "\\tag{6}\n",
    "\\end{equation}\n",
    "$$\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Barring the gates used in the state preparation step, the circuit starts off by implementing a Hadamard gate and then $n-1$ rotations on the zeroth qubit - a total of $n$ gates. This is followed by a Hadamard and $n-2$ conditional rotations on the first qubit which totals to $n -1$ gates. If we continue the series, we get $n + (n-1) + (n-2)... = n(n+1)/2$ gates. Hence, this circuit provides an algorithm with $O(n^2)$ gates for computing the QFT. \n",
    "\n",
    "The best classical algorithms for computing fast Fourier transforms on $2^{n}$ elements require $O(n2^{n})$ gates. This means that it requires exponentially more operations to compute the fast Fourier transform on a classical computer than it does to implement the QFT on a quantum computer.\n",
    "\n",
    "Why are we not using QFT for real life applications then? The problem lies in quantum measurement. The quantum-Fourier-transformed amplitudes cannot be accessed by quantum measurement. However there are other quantum algorithms that do make use of QFT such as Shor's algorithm. \n",
    "\n",
    "One can also invert the QFT where the circuit is executed in reverse with the inverse of each gate. The figure below shows the general $n$-qubit inverse QFT. Why don't you try implementing this in CUDA-Q?\n",
    "\n",
    "<img src=\"images/inverse_qft.png\" alt=\"qft\" width=\"600\">\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Quantum Fourier Transform revisited\n",
    "We provided one implementation of the Quantum Fourier Transform above.  To demonstrate some of the other features of CUDA-Q, let's define a new kernel for the Quantum Fourier Transform, which we'll call `quantum_fourier_transform2`.  Pay attention to how the kernel definition differs from the example above.\n",
    "\n",
    " Since the Quantum Fourier Transform is a unitary operator, its inverse is its adjoint.  Therefore, once we have implemented the Quantum Fourier Transform as a kernel in CUDA-Q, we can use the built-in `adjoint` operation to create the Inverse Quantum Fourier Transform."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define kernels for the Quantum Fourier Transform and the Inverse Quantum Fourier Transform\n",
    "@cudaq.kernel\n",
    "def quantum_fourier_transform2(qubits: cudaq.qview):\n",
    "    '''Args: \n",
    "    qubits (cudaq.qview): specifies the quantum register to which apply the QFT.'''\n",
    "    qubit_count = len(qubits)\n",
    "    # Apply Hadamard gates and controlled rotation gates.\n",
    "    for i in range(qubit_count):\n",
    "        h(qubits[i])\n",
    "        for j in range(i + 1, qubit_count):\n",
    "            angle = (2 * np.pi) / (2**(j - i + 1))\n",
    "            cr1(angle, [qubits[j]], qubits[i])\n",
    "\n",
    "\n",
    "@cudaq.kernel\n",
    "def inverse_qft(qubits: cudaq.qview):\n",
    "    '''Args: \n",
    "    qubits (cudaq.qview): specifies the quantum register to which apply the inverse QFT.'''\n",
    "    cudaq.adjoint(quantum_fourier_transform2, qubits)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's see that this approach gives us the same results as the section above. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     ╭───╮╭───╮╭─────────╮╭──────────╮                                      »\n",
      "q0 : ┤ x ├┤ h ├┤ r1(1.5) ├┤ r1(0.75) ├──────────────────────────────────────»\n",
      "     ╰───╯╰───╯╰────┬────╯╰────┬─────╯╭───╮╭─────────╮          ╭──────────╮»\n",
      "q1 : ───────────────●──────────┼──────┤ h ├┤ r1(1.5) ├──────────┤ r1(-1.5) ├»\n",
      "     ╭───╮                     │      ╰───╯╰────┬────╯╭───╮╭───╮╰────┬─────╯»\n",
      "q2 : ┤ x ├─────────────────────●────────────────●─────┤ h ├┤ h ├─────●──────»\n",
      "     ╰───╯                                            ╰───╯╰───╯            »\n",
      "\n",
      "################################################################################\n",
      "\n",
      "     ╭───────────╮╭──────────╮╭───╮\n",
      "─────┤ r1(-0.75) ├┤ r1(-1.5) ├┤ h ├\n",
      "╭───╮╰─────┬─────╯╰────┬─────╯╰───╯\n",
      "┤ h ├──────┼───────────●───────────\n",
      "╰───╯      │                       \n",
      "───────────●───────────────────────\n",
      "                                   \n",
      "\n",
      "[0.+0.j 0.+0.j 0.+0.j 0.+0.j 0.+0.j 1.-0.j 0.-0.j 0.+0.j]\n"
     ]
    }
   ],
   "source": [
    "@cudaq.kernel\n",
    "def verification_example(input_state: List[int]):\n",
    "    '''Args: \n",
    "    input_state (list[int]): specifies the input state to be transformed with QFT and the inverse QFT.  '''\n",
    "    qubit_count = len(input_state)\n",
    "    # Initialize qubits.\n",
    "    qubits = cudaq.qvector(qubit_count)\n",
    "\n",
    "    # Initialize the quantum circuit to the initial state.\n",
    "    for i in range(qubit_count):\n",
    "        if input_state[i] == 1:\n",
    "            x(qubits[i])\n",
    "\n",
    "    # Apply the quantum Fourier Transform\n",
    "    quantum_fourier_transform2(qubits)\n",
    "\n",
    "    # Apply the inverse quantum Fourier Transform\n",
    "    inverse_qft(qubits)\n",
    "\n",
    "\n",
    "# The state to which the QFT operation is applied to. The zeroth element in the list is the zeroth qubit.\n",
    "input_state = [1, 0, 1]\n",
    "\n",
    "# Number of decimal points to round up the statevector to.\n",
    "precision = 2\n",
    "\n",
    "print(cudaq.draw(verification_example, input_state))\n",
    "\n",
    "# Print the statevector to the specified precision\n",
    "statevector = np.array(cudaq.get_state(verification_example, input_state))\n",
    "print(np.round(statevector, precision))  # The result should be the input state"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CUDA-Q Version latest (https://github.com/NVIDIA/cuda-quantum a726804916fd397408cbf595ce6fe5f33dcd8b4c)\n"
     ]
    }
   ],
   "source": [
    "print(cudaq.__version__)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
